﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using GKQC.DbHelper.ViewModels;
using GKQC.Language;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GKQC.Ort
{
    public partial class FormQuery : Form
    {
        public OrtFilter Filter;
        UserModel _User;
        public List<ReportSetModel> _ReportSetModels;

        AllDbContext dbContext = null;
        //OrtViewModel ortViewModel = null;
        FormStatus _FormStatus = FormStatus.Browser;
        OrtHeadModel _CurrentHead = null;
        List<OrtHeadModel> _Heads = null;
        OrtService _OrtService = null;
        string _BillType = string.Empty;
        List<OrtDtlModel> _EmptyDtlModels = new List<OrtDtlModel>();
        /// <summary>
        /// 单号
        /// </summary>
        public string BillNo { get; set; }
        /// <summary>
        /// 测试次数
        /// </summary>
        public int SNo { get; set; }


        public FormQuery(UserModel user, string billType, List<ReportSetModel> reportSetModels)
        {
            InitializeComponent();
            try
            {
                this._User = user;
                this._ReportSetModels = reportSetModels;
                this._BillType = billType;
                _OrtService = new OrtService(new AllDbContext());
                if (Filter == null)
                {
                    Filter = new OrtFilter();
                    var date = this._User.GetServerTime();
                    Filter.StartModiDate = date.AddYears(-5);
                    Filter.EndModiDate = date.AddYears(1);
                    Filter.StartTestDate = Filter.StartModiDate;
                    Filter.EndTestDate = Filter.EndModiDate;
                    Filter.StartFinishDate = Filter.StartModiDate;
                    Filter.EndFinishDate = Filter.EndModiDate;
                    Filter.StartExpireDate = Filter.StartModiDate;
                    Filter.EndExpireDate = Filter.EndModiDate;
                    Filter.BillType = billType;
                    Filter.AllBill = false;
                    Filter.RowCount = 20;
                }

                this.MainDataGridView.AutoGenerateColumns = false;
                this.MainDataGridView.RowPostPaint += DataGridViewSet.RowPostPaint;
                this.MainDataGridView.RowEnter += MainDataGridView_RowEnter;

                this.DtlDataGridView.AutoGenerateColumns = false;

                GetReportSet();

                BindingControls();
                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0028", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void SetBillNo(string billNo)
        {
            txtBillNo.Text = billNo;
            Filter.BillNo = billNo;
        }

        private void MainDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                OrtHeadModel head = null;
                if (MainDataGridView.Rows.Count > 0)
                    head = MainDataGridView.Rows[e.RowIndex].DataBoundItem as OrtHeadModel;
                if (_CurrentHead == head) return;
                _CurrentHead = head;
                if (_CurrentHead == null) _CurrentHead = new OrtHeadModel();
                int currentRowIndex = _Heads.IndexOf(_CurrentHead);

                if (_CurrentHead.Dtls == null || _CurrentHead.Dtls.Count == 0)
                {
                    List<OrtDtlModel> dtls = _OrtService.GetDtls(_CurrentHead.Id);
                    if (dtls != null && dtls.Count > 0)
                        _CurrentHead.Dtls = dtls;
                }
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);

                BindingControls();
                MainDataGridView.Focus();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0021"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetReportSet()
        {
            try
            {
                if (_ReportSetModels != null)
                {
                    cboReport.DisplayMember = "Name";
                    cboReport.ValueMember = "Id";
                    cboReport.DataSource = _ReportSetModels;

                    ColReportId.DataPropertyName = "";
                    ColReportId.DataSource = new BindingList<ReportSetModel>(_ReportSetModels);
                    ColReportId.ValueType = typeof(ReportSetModel);
                    ColReportId.DisplayMember = "Name";
                    ColReportId.ValueMember = "Id";
                    ColReportId.DataPropertyName = "ReportId";
                }
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0020", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BindingControls()
        {
            txtBillNo.DataBindings.Clear();
            txtLotNo.DataBindings.Clear();
            numRowCount.DataBindings.Clear();
            cboReport.DataBindings.Clear();

            if (Filter == null) return;
            txtBillNo.DataBindings.Add("Text", Filter, "BillNo");
            txtLotNo.DataBindings.Add("Text", Filter, "LotNo");
            numRowCount.DataBindings.Add("Value", Filter, "RowCount");
            cboReport.DataBindings.Add("SelectedValue", Filter, "ReportId");
        }

        private void splitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight("FormOrt", this._User, RightType.Query))
            {
                return;
            }

            try
            {
                if (!this.Validate()) return;
                 BindingData();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0029", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void BindingData()
        {
            try
            {
                DtlDataGridView.DataSource = _EmptyDtlModels;

                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (s, a) =>
                {
                    AllDbContext db = new AllDbContext();
                    var OrtService1 = new OrtService(db);
                    _Heads = OrtService1.Query(Filter);
                };
                worker.RunWorkerCompleted += (s, a) =>
                {
                    MainDataGridView.DataSource = new BindingList<OrtHeadModel>(_Heads);
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, 0));
                };

                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0008"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                this.BillNo = string.Empty;
                this.SNo = 1;

                if (MainDataGridView.CurrentCell != null)
                {
                    OrtHeadModel head = MainDataGridView.Rows[MainDataGridView.CurrentCell.RowIndex].DataBoundItem as OrtHeadModel;
                    if (head != null)
                    {
                        this.BillNo = head.BillNo;
                        this.SNo = head.Dtls.Max(t => t.SNo);
                        this.DialogResult = DialogResult.OK;
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }

        }

        private void MainDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            btnOk_Click(btnOk, new EventArgs());
        }

        private void MainDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void FormQuery_Shown(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtBillNo.Text))
            {
                BindingData();
            }
        }
    }
}
